package com.yinp.proapp.greendao;

import com.yinp.proapp.base.App;

import org.greenrobot.greendao.AbstractDao;

import java.util.List;

/**
 * @author :yinpeng
 * date      :2021/8/31
 * package   :com.yinp.mygreendao.greendao
 * describe  :
 */
public class DaoUtils<T> {
    protected DaoSession mDaoSession;
    protected Class<T> entityClass;
    protected AbstractDao<T, Long> entityDao;
    public static final int size = 10;

    public DaoUtils(Class<T> clazz, AbstractDao<T, Long> pEntityDao) {
        mDaoSession = App.daoSession;
        entityClass = clazz;
        entityDao = pEntityDao;
    }

    /**
     * 插入记录，如果表未创建，先创建表
     */
    public boolean insert(T pEntity) {
        return entityDao.insert(pEntity) != -1;
    }

    public void update(T pEntity) {
        entityDao.update(pEntity);
    }
    public void delete(T pEntity) {
        entityDao.delete(pEntity);
    }
    public boolean saveList(final List<T> pEntityList) {
        return saveList(pEntityList, false);
    }

    public boolean saveList(final List<T> pEntityList, final boolean isReplace) {
        if (pEntityList != null && pEntityList.size() > 0) {
            try {
                mDaoSession.runInTx(new Runnable() {
                    @Override
                    public void run() {
                        for (T entity : pEntityList) {
                            if (isReplace) {
                                mDaoSession.insertOrReplace(entity);
                            } else {
                                mDaoSession.insert(entity);
                            }
                        }
                    }
                });
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 通过页数查询，默认每页10条
     * 查询时从第0页开始的
     *
     * @param clazz
     * @param pageNo
     * @return
     */
    public List<T> queryPageList(Class<T> clazz, int pageNo) {
        return queryPageList(clazz, pageNo, size);
    }

    public List<T> queryPageList(Class<T> clazz, int pageNo, int pageSize) {
        if (pageNo <= 0) {
            return null;
        }
        return mDaoSession.queryBuilder(clazz).offset((pageNo - 1) * pageSize).limit(pageSize).list();
    }
}
